package ro.flashbite.game_engine.view.sheet.gpu
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.PixelSnapping;
	import flash.geom.Rectangle;
	
	import ro.flashbite.errors.ArgumentIncompatibleError;
	
	/**
	 * Base class that extends SimpleSpriteSheetGPU, but is uses instead vectors of BitmapData and XML to draw visuals with extra speed.
	 * Can only play frame bases animation; No FrameLabels are recognized; This class use visibility of all bitmaps to show current frame
	 *  
	 * v 1.0
	 * 
	 * @author Adrian Barbu
	 */
	public final class ComplexSpriteSheetGPU extends SimpleSpriteSheetGPU
	{
		public function ComplexSpriteSheetGPU(sheetBmpData:Vector.<BitmapData>, settingsXMLs:Vector.<XML>)
		{
			super(null, null);
			
			_constructor(sheetBmpData, settingsXMLs);
		}
		private function _constructor(sheetBmpData:Vector.<BitmapData>, settingsXMLs:Vector.<XML>):void
		{
			if (sheetBmpData == null) throw new ArgumentIncompatibleError("sheetBmpData");
			if (settingsXMLs == null) throw new ArgumentIncompatibleError("settingsXMLs");
			
			var len1:uint = sheetBmpData.length,
				len2:uint = settingsXMLs.length;
			if (len1 != len2) throw new Error("sheetBmpData.length() != settingsXMLs.length()");
			
			
			_allBmpFrames = new Vector.<Bitmap>();
			//create and save bitmaps
			var rectangles:Vector.<Rectangle> = new Vector.<Rectangle>(),
				xmlListSlices:XMLList,
				i:uint,
				j:uint,
				len:uint,
				xmlSlice:XML,
				rect:Rectangle,
				bmpData:BitmapData,
				bmp:Bitmap,
				currentBmpData:BitmapData,
				currentXML:XML;
			
			
			
			for (i = 0; i < len1; i++) {
				//set locations
				currentBmpData = sheetBmpData[i] as BitmapData;
				currentXML = settingsXMLs[i] as XML;
				//read in each xml + save rectangles and bitmapDatas in
				xmlListSlices = currentXML.slices.slice as XMLList;
				len = xmlListSlices.length();
				
				for (j = 0; j < len; j++) {
					xmlSlice = xmlListSlices[j];
					
					rect = new Rectangle(Number(xmlSlice.@x), Number(xmlSlice.@y), Number(xmlSlice.@width), Number(xmlSlice.@height));
					bmpData = new BitmapData(rect.width, rect.height, true, 0x00FFFFFF);
					bmpData.copyPixels(currentBmpData, rect, DEFAULT_POINT);
					bmp = new Bitmap(bmpData, PixelSnapping.NEVER, true);
					
					_allBmpFrames.push(bmp);
					
					this.addChild(bmp); 
					
					bmp.visible = false;
				}
			}
			
			//set total frames
			_totalFrames = _allBmpFrames.length;
			
			//stop it on frame 1
			_currentFrame = 1; // set this for non extra-check on set currentFrame 
			gotoAndStop(1);
			
			//disable interaction
			disable();
		}
	}
}